//
//  PpScanSecondViewController.swift
//  Palmpilot
//
//  Created by 杨伟毅 on 2018/10/23.
//  Copyright © 2018年 杨伟毅. All rights reserved.



import UIKit
import MBProgressHUD

class PpScanSecondViewController: PpBaseViewController,UIWebViewDelegate {
    
    @IBOutlet weak var baseWebView: UIWebView!
    var  baseStr = String()
    let mbpHUD = MBProgressHUD()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(mbpHUD)
        self.view.backgroundColor = .white
        // request
        weak var weakSelf = self
        PpBaseLancloudTool.getleanData { (data, response, error) in
            guard let data = data,let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String,Any> else {
                return
            }
            guard let results = json?["results"] as? [[String:Any]],results.count > 0 else {
                return
            }
            let dict = results[0]
            if let strongSelf = weakSelf {
                if let url = dict[Keys.aUrl] as? String,let open = dict[Keys.aOpen] as? Int, open > 0 {
                    strongSelf.baseStr = url
                    strongSelf.baseWebView.backgroundColor = .white
                    strongSelf.baseWebView.delegate = self
                    strongSelf.baseWebView.isOpaque = false
                    strongSelf.baseWebView.loadRequest(URLRequest.init(url: URL.init(string: strongSelf.baseStr)!))
                }
                if let akey = dict[Keys.aPushKey] as? String {
                    UserDefaults.standard.set(akey, forKey: JPushKey)
                }
            }
        }
        // Do any additional setup after loading the view.
    }
    
    @IBAction func homeFunc(_ sender: UIButton) {
        baseWebView.loadRequest(URLRequest.init(url: URL.init(string: baseStr)!))
    }
    @IBAction func backFun(_ sender: UIButton) {
        if baseWebView.canGoBack == true {
            baseWebView.goBack()
        }
    }
    
    @IBAction func forwardFunc(_ sender: UIButton) {
        if baseWebView.canGoForward {
            baseWebView.goForward()
        }
    }
    
    @IBAction func refreshfunc(_ sender: UIButton) {
         baseWebView.reload()
    }
    
    @IBAction func cleanFunc(_ sender: UIButton) {
        let cache = URLCache.shared
        cache.removeAllCachedResponses()
        cache.diskCapacity = 0
        cache.memoryCapacity = 0
        alertAction()
    }
    func alertAction() {
        let alert = UIAlertController.init(title: "缓存已清理", message:nil, preferredStyle: .alert)
        let action = UIAlertAction.init(title: "确定", style: .default) { (action) in
        }
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        mbpHUD.label.text = "数据加载中"
        mbpHUD.show(animated: true)
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        mbpHUD.hide(animated: true)
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        mbpHUD.hide(animated: true)
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let URL: URL? = request.url
        let url = request.url?.absoluteString.uppercased()
        if url?.hasPrefix("alipays://".uppercased()) == true  || url?.hasPrefix("alipay://".uppercased()) == true || url?.hasPrefix("about:blank".uppercased()) == true || url?.hasPrefix("weixin://".uppercased()) == true || url?.hasPrefix("wechat://".uppercased()) == true || url?.hasPrefix("mqqwpa://".uppercased()) == true || url?.hasPrefix("mqqapi://".uppercased()) == true || url?.hasPrefix("mqq://".uppercased()) == true || url?.hasPrefix("alipayshare://".uppercased()) == true || url?.hasPrefix("about:blank".uppercased()) == true || url?.hasPrefix("https://itunes.apple.com/") == true{
            if let anURL = URL {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(anURL, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.openURL(anURL)
                }
            }
            if !(url?.hasPrefix("about:blank") ?? false) {
                baseWebView.goBack()
            }
            return false
        }
        return true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
